package com.songlei.rtcadriondh265demo.rtc

import android.util.Log
import org.webrtc.DefaultVideoEncoderFactory
import org.webrtc.EglBase
import org.webrtc.VideoCodecInfo
import org.webrtc.VideoEncoder

class PreferredVideoEncoderFactory(
    eglBaseContext: EglBase.Context?,
    enableIntelVp8Encoder: Boolean,
    enableH264HighProfile: Boolean
) : DefaultVideoEncoderFactory(eglBaseContext, enableIntelVp8Encoder, enableH264HighProfile) {

    companion object {
        private const val TAG = "PreferredVideoEncoderFactory"
        private const val TARGET_CODEC = "H265"
        private const val FALLBACK_CODEC = "H264"
    }

    private val validH265Codecs = mutableListOf<VideoCodecInfo>()

    init {
        // 初始化时验证 H265 编码器可用性
        super.getSupportedCodecs()
            .filter { it.name.equals(TARGET_CODEC, true) }
            .forEach { codecInfo ->
                if (tryCreateEncoderWithFallback(codecInfo) != null) {
                    validH265Codecs.add(codecInfo)
                }
            }

        Log.i(TAG, "可用 H265 编码器数量: ${validH265Codecs.size}")
        if (validH265Codecs.isEmpty()) {
            Log.w(TAG, "当前设备不支持 $TARGET_CODEC 编码格式")
        }
    }

    override fun createEncoder(info: VideoCodecInfo): VideoEncoder? {
        // 优先尝试创建 H265 编码器
        return when {
            info.name.equals(TARGET_CODEC, true) -> tryCreateEncoderWithFallback(info)
            else -> super.createEncoder(info)
        }
    }

    private fun tryCreateEncoderWithFallback(info: VideoCodecInfo): VideoEncoder? {
        return super.createEncoder(info)?.also {
            Log.i(TAG, "成功创建 ${info.name} 编码器（${info.params}）")
        } ?: run {
            Log.w(TAG, "创建 ${info.name} 编码器失败，可能原因：" +
                    "\n- 系统解码器缺失" +
                    "\n- 硬件不支持" +
                    "\n- 权限限制")
            null
        }
    }

    override fun getSupportedCodecs(): Array<VideoCodecInfo> {
        val originalCodecs = super.getSupportedCodecs().toList()

        // 分离 H264 和其他编码格式
        val remainingCodecs = originalCodecs.filterNot { it.name.equals(TARGET_CODEC, true) }
        val (h264Codecs, otherCodecs) = remainingCodecs.partition {
            it.name.equals(FALLBACK_CODEC, true)
        }

        // 构建优先级列表：H265 > H264 > 其他
        return mutableListOf<VideoCodecInfo>().apply {
            addAll(validH265Codecs)   // 已验证可用的 H265
            addAll(h264Codecs)        // 原生支持的 H264
            addAll(otherCodecs)      // 其他编码格式（VP8/VP9等）
        }.toTypedArray()
    }
}